package com.xcity.game.activity2.platform.j9kgames;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcity.db.entity.Activity;
import com.xcity.db.entity.Player;
import com.xcity.game.account.AccountChannel;
import com.xcity.game.activity2.ActivityImpl;
import com.xcity.game.activity2.platform.IPacketHandler;
import com.xcity.game.activity2.platform.PlatformGift;
import com.xcity.game.activity2.platform.PlatformGiftDispatchService;
import com.xcity.game.common.Cause;
import com.xcity.game.common.IRegistry;
import com.xcity.game.common.MessageConst;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.event.GameEvents;
import com.xcity.pomelo.push.msg.PlatformGiftPush;
import com.xcity.pomelo.request.PlatformGiftInfoRequest;
import com.xcity.pomelo.request.PlatformGiftRequest;
import com.xcity.pomelo.response.PlatformGiftInfoResponse;
import com.xcity.util.HttpUtils;
import com.xcity.util.PlatformApi;

import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.net.Session;
import naga.x.service.ServiceException;

/**
 * 游戏金榜礼包（关注礼包）
 * @author yang.li
 *
 */
public class J9KGamesGiftActivity extends ActivityImpl implements IPacketHandler, EventListener {

	private IRegistry<AccountChannel, IPacketHandler> registry;
	private PlatformGift gift;
	
	public J9KGamesGiftActivity(Activity entity) {
		super(entity);
		this.registry = App.getApp().getServiceManager().get(PlatformGiftDispatchService.class);
	}

	@Override
	public String getId() {
		return getClass().getName();
	}

	@Override
	public void init() {
		gift = entity.getDataObj(PlatformGift.class);
	}

	@Override
	public void save() {
	}

	@Override
	public void startup() throws ServiceException {
		registry.register(AccountChannel.J9KGAMES, this);
		App.getApp().getEventManager().register(this);
	}

	@Override
	public void shutdown() throws ServiceException {
		registry.unRegister(AccountChannel.J9KGAMES);
		App.getApp().getEventManager().unRegister(this);
	}

	@Override
	public boolean update() {
		return true;
	}

	@Override
	public void setDirty() {
		init();
	}
	
	@Override
	public int[] getEventTypes() {
		return new int[] { GameEvents.EVENT_PLAYER_LOADED };
	}

	@Override
	public void handleEvent(Event event) {
		playerLoaded(event.getParameter(0));
	}
	
	private void playerLoaded(Player player) {
		receive(player, gift);
	}

	@Override
	public void requestGiftInfo(Session session, PlatformGiftInfoRequest req) {
		Player player = session.getClient();
		byte state = getState(player, gift);
		session.send(new PlatformGiftInfoResponse(req.getSerial(), gift, state));
	}
	
	@Override
	public void requestGift(Session session, PlatformGiftRequest req) {
		Player player = session.getClient();
		String error = receive(player, gift);
		if (error != null) {
//			session.send(new HintResponse(req.getSerial(), error));
			session.send(new PlatformGiftInfoResponse(req.getSerial(), gift, getState(player, gift)));
			return;
		}
//		session.send(new Response(req.getSerial()));
		session.send(new PlatformGiftInfoResponse(req.getSerial(), gift, PlatformGift.STATE_RECEIVE_SUCC));
	}
	
	private String receive(Player player, PlatformGift gift) {
		byte state = getState(player, gift);
		if (state == PlatformGift.STATE_CAN_NOT_RECEIVE) {
			return MessageConst.EXCHANGE_CAN_NOT_RECEIVE;
		}
		if (state == PlatformGift.STATE_RECEIVED) {
			return MessageConst.EXCHANGE_RECEIVED;
		}
		player.poolSet(getPoolKey(gift), gift.id);
		gift.content.receive(player, Cause.J9KGAMES_GIFT, false);
		player.send(new PlatformGiftPush(gift, PlatformGift.STATE_RECEIVED));
		return null;
	}

	private byte getState(Player player, PlatformGift gift) {
		String poolKey = getPoolKey(gift);
		int id = player.getPool().getInt(poolKey, PlatformGift.STATE_CAN_NOT_RECEIVE);
		if (id == PlatformGift.STATE_CAN_NOT_RECEIVE) {
			try {
				String uid = AccountChannel.J9KGAMES.withoutPrefix(player.getAccount().getChannelUid());
				String res = HttpUtils.post(PlatformApi.j9kgamesSubscribeUrl, new String[] { "uid", uid });
				JSONObject resObj = JSON.parseObject(res);
				if (resObj != null && resObj.getIntValue("code") == 0 && "1".equals(resObj.getString("message"))) {
					// 已关注过公众号
					player.poolSet(poolKey, PlatformGift.STATE_CAN_RECEIVE);
					return PlatformGift.STATE_CAN_RECEIVE;
				}
			} catch (Exception e) {
				LOG.error("[99KGAMES PLATFORM REQ ERR]ID[" + player.getId() + "]", e);
			}
			return PlatformGift.STATE_CAN_NOT_RECEIVE;
		}
		if (id == gift.id) {
			return PlatformGift.STATE_RECEIVED;
		}
		return PlatformGift.STATE_CAN_RECEIVE;
	}
	
	private static String getPoolKey(PlatformGift gift) {
		return PlayerPool.PROPERTY_99KGAMES_GIFT_PREFIX + gift.type;
	}

}
